from urllib.request import *
from urllib.parse import urlencode

from os.path import join

import config
config = config.Config()

def readAuthorised(url):
    print("Reading %s" % url)
    res = urlopen(url, data=bytes(urlencode(config.access), encoding="UTF-8"))
    ans = res.read()
    return ans

def request_contest_xml(id):
    import xml.etree.ElementTree as ET
    return ET.XML(readAuthorised(
            '%s/c/%s/contest.xml' % (
                config.polygon_url, id)))

def download_statement(dst_dir, xml, lang = "russian"):
    for node in xml.findall("*/statement"):
        if node.get("language") == lang: 
            res_file = join(dst_dir, "statement.pdf")
            urlretrieve(
                    node.get("url"),
                    res_file,
                    data = urlencode(config.access))
            return res_file

    return None

def extract_contest_name(xml, lang = "russian"):
    for node in xml.findall("*/name"):
        if node.get("language") == lang: 
            return node.get("value")

